package com.nj.interfaces.actions.uploadpicture.service;

import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import sun.misc.BASE64Decoder;

import com.nj.framework.util.ReadConfig;
import com.nj.interfaces.actions.uploadpicture.dao.UserPictureDAO;


/**
 * 项目名称：  LawSchool   
 * 类名称：  UserPictureService   
 * 描述：  
 * @author  吴志虎   
 * 创建时间：  2016年1月14日 下午7:04:14 
 *
 */
@Service
public class UserPictureService {
	private static final Log logger = LogFactory.getLog(UserPictureService.class);

	@Autowired
	private UserPictureDAO pictureDAO;
	
	/**
	 * 
	* uploadMobileOriginalPicture  移动端上传用户头像图片
	* @param    
	* @return  
	* @throws 
	* @since  CodingExample　Ver(编码范例查看) 1.1
	 */
	public Map<String, Object> uploadMobileOriginalPicture(HttpServletRequest request) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("operFlag", "0");
		String errorMessage = "";
		String imageName = request.getParameter("imageName");//图片名称，例如moon.jpg
		String imageBody = request.getParameter("imageBody");//经过编码的图片文件字符
		try {
			if (imageName == null || "".equals(imageName) || imageBody == null || "".equals(imageBody)) {
				result.put("operCode", "000188");// 未找到name为file的图片文件
				result.put("operDesc", "未找到name为file的图片文件");// 
				return result;
			}
			// 获得文件名：
			String subName = imageName.substring(imageName.lastIndexOf(".") + 1);
			String fileName = System.currentTimeMillis() + "." + subName; 
			if (!vaildateFile(subName)) {
				result.put("operCode", "000189");// 图片文件格式不正确
				result.put("operDesc", "图片文件格式不正确");// 
				return result;
			}
			String originalPath = "/temp/picture/original/";
			String basePath = request.getServletContext().getRealPath("") + originalPath;
			File tempDir = new File(basePath);
			if (!tempDir.exists()) {
				tempDir.mkdirs();
			}

			String imgUrl = originalPath + fileName;
			boolean success = generateImage(basePath + fileName, imageBody);
			if (success) {
				result.put("operFlag", "1");
				result.put("imgUrl", imgUrl);
			} else {
				result.put("operCode", "000039");// 系统异常
				result.put("operDesc", "系统异常");// 
				return result;
			}			
		} catch (Exception e) {
			result.put("operCode", "000039");// 系统异常
			result.put("operDesc", "系统异常");//
			result.put("errorMessage", errorMessage);
			logger.error("上传用户头像原始图片文件至服务器临时目录异常，信息：", e);
		}

		return result;
	}
	
	
	
	/**
	 * 
	* vaildateFile  验证图片格式
	* @param    
	* @return  
	* @throws 
	* @since  CodingExample　Ver(编码范例查看) 1.1
	 */
	private boolean vaildateFile(String subName) {
		if (subName == null || "".equals(subName))
			return false;
		subName = subName.toLowerCase();
		String uploadImg = "(png|jpg|jpeg|bmp){1}";
		return subName.matches(uploadImg);
	}
	
	/**
	 * 
	* generateImage  对字节数组字符串进行Base64解码并生成图片
	* @param    
	* @return  
	* @throws 
	* @since  CodingExample　Ver(编码范例查看) 1.1
	 */
	private boolean generateImage(String imgFilePath, String imgStr) {
		if (imgStr == null) { //图像数据为空
			return false;
		}
		BASE64Decoder decoder = new BASE64Decoder();
		OutputStream out = null;
		try {
			byte[] b = decoder.decodeBuffer(imgStr);
			for(int i = 0; i < b.length; ++i) {
				//调整异常数据
				if(b[i] < 0) {
					b[i] += 256;
				}
			}
			//生成图片
			out = new FileOutputStream(imgFilePath);
			out.write(b);
			out.flush();
			return true;
		} catch (Exception e) {
			logger.error("通过base64编码生成图片失败", e);
			return false;
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (Exception e1) {
				logger.error("通过base64编码生成图片失败", e1);
			}
		}
	}
	/**
	 * 
	* upload2ImageServer  上传文件至图片服务器
	* @param    
	* @return  
	* @throws 
	* @since  CodingExample　Ver(编码范例查看) 1.1
	 *//*
	public Map<String, Object> upload2ImageServer(HttpServletRequest request, String cutImgUrl, boolean compressFlag) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("operFlag", "0");
		String errorMessage = "";
		
		String userId = request.getParameter("userId");//上传用户
		String imageDesc = request.getParameter("imageDesc");//图片描述
		InputStream input = null;
		OutputStream outPut = null;
		
		String folderId = "3";//目录Id
		String imageClassId = "1";//图片类别
		String imageName = "HeadImg";//图片名称
		String busyId = "1";//业务编码
		String busyCode = "tts";
		Map<String, Object> busyInfo = pictureDAO.selectBusyInfo(new BigDecimal(imageClassId));
		if (busyInfo != null) {
			busyId = MapUtils.getString(busyInfo, "PK_BUSY_CODE_ID", "1");
			busyCode = MapUtils.getString(busyInfo, "BUSY_CODE_CODE", "tts");
		}
		
		Long imagePk = pictureDAO.selectImagePK();
		String nowDate = DateFormatUtils.format(new Date(), "yyyyMMdd");// 可以方便地修改日期格式
		String fileType = cutImgUrl.substring(cutImgUrl.lastIndexOf(".") + 1).toLowerCase();
		
		try {
			*//****************************下面是存图片到服务器本地*****************************//*
			File file = new File(request.getServletContext().getRealPath("") + cutImgUrl);
	        
	        input = new FileInputStream(file);// 获得输入流：   
	        FileUtil.isExist(ReadConfig.getProp("imgPath") + busyCode + "_old/" + nowDate + "/");
	        outPut = new FileOutputStream(ReadConfig.getProp("imgPath") + busyCode + "_old/" + nowDate + "/" + imagePk + "." + fileType);
	        byte[] buffer = new byte[1024]; 
	        int len = 0;
	        //读入流，保存至byte数组
	        while((len = input.read(buffer))>0){ 
	        	outPut.write(buffer,0,len);
	        }
	        *//********************************上面是存图片到服务器本地***************************//*
	        Image img = ImageIO.read(file);
			int imageW = img.getWidth(null);
			int imageH = img.getHeight(null);
	        
	        String originalPath = busyCode + "_old/" + nowDate + "/" + imagePk + "." + fileType;
	        String newPath = busyCode + "_new/" + nowDate + "/" + imagePk + "." + fileType;
	        String iconFilePath = busyCode + "_icon/" + nowDate + "/" + imagePk + "." + fileType;
	        String encryptPath = ImageCryptUtil.getInstance().encryptAES(newPath);
	        
	        //new_path对应的图片
	        if (compressFlag) {//需要压缩，默认压缩0.8
	        	ImageCompress.doCompressV2(file, ReadConfig.getProp("imgPath"), newPath,
					imageW, imageH, 0.8f);
	        } else {//不压缩，直接文件复制
	        	FileUtils.copyFile(file, new File(ReadConfig.getProp("imgPath") + newPath));
	        }
	        //缩略图
			ImageCompress.doCompressV2(file, ReadConfig.getProp("imgPath"), iconFilePath,
					100, 100, 0.8f);	        
	        
	        pictureDAO.insertDBImage(imagePk, folderId, busyId, userId, imageName, 
	        		originalPath, newPath, sourceId, fileType, file.length(), imageDesc, imageClassId,
	        		new BigDecimal(imageW), new BigDecimal(imageH), iconFilePath, encryptPath);
	        
	        result.put("operFlag", "1");
	        result.put("imgId", imagePk);
	        result.put("picUrl", ImageCryptUtil.getInstance().encryptAES(originalPath));
		} catch (Exception e) {
			errorMessage = ExceptionUtil.getStackTrace(e);
			result.put("operCode", "000039");// 系统异常
			result.put("errorMessage", errorMessage);
			logger.error("上传图片文件至图片服务器异常，信息：", e);
		} finally {
			try {
				if(outPut != null) {
					outPut.close();
				}
				if(input != null) {
					input.close();
				}
			} catch (Exception e2) {
				result.put("operCode", "000039");// 系统异常
				result.put("errorMessage", errorMessage);
				logger.error("上传图片文件至图片服务器异常，信息：", e2);
			}
		}
		
		return result;
	}
*/
}
